"""
模拟数据生成器
用于开发阶段生成符合API规范的测试数据
"""
import random
from datetime import datetime, timedelta
from typing import List, Dict, Any


class MockDataGenerator:
    """模拟数据生成器"""

    @staticmethod
    def generate_time_labels(hours: int = 24) -> List[str]:
        """生成时间标签"""
        return [f"{i:02d}:00" for i in range(hours)]

    @staticmethod
    def generate_random_series(length: int, min_val: int, max_val: int) -> List[int]:
        """生成随机数据序列"""
        return [random.randint(min_val, max_val) for _ in range(length)]

    # ==================== 总览模块 ====================
    @staticmethod
    def generate_overview_data() -> Dict[str, Any]:
        """生成总览数据"""
        return {
            "systemStatus": {
                "status": "running",
                "uptime": f"{random.randint(12, 72)} 小时",
                "lastUpdate": datetime.now().isoformat(),
            },
            "realTimeStats": {
                "totalPeople": 18500,
                "departure": 6500,
                "retention": 12000,
                "background": 11000,
                "activity": 7500,
                "normalCount": 18350,
                "anomalyCount": 150,
            },
            "modelsPerformance": [
                {
                    "model": "离场/停留识别",
                    "algorithm": "Transformer",
                    "accuracy": 0.85,
                    "f1": 0.83,
                },
                {
                    "model": "背景/活动区分",
                    "algorithm": "DBSCAN+决策树",
                    "accuracy": 0.8678,
                    "f1": 0.8631,
                },
                {
                    "model": "异常检测(微观)",
                    "algorithm": "LightGBM",
                    "accuracy": 0.95,
                    "f1": 0.9442,
                },
                {
                    "model": "异常检测(中观)",
                    "algorithm": "LightGBM",
                    "accuracy": 0.96,
                    "f1": 0.9644,
                },
            ],
            "recentAlerts": [
                {
                    "time": "2分钟前",
                    "type": "群体异常",
                    "level": "high",
                    "message": "BS-003基站检测到突发聚集",
                },
                {
                    "time": "15分钟前",
                    "type": "轨迹异常",
                    "level": "medium",
                    "message": "北入口检测到异常移动模式",
                },
                {
                    "time": "30分钟前",
                    "type": "流量异常",
                    "level": "low",
                    "message": "南入口人流量突增",
                },
            ],
        }

    @staticmethod
    def generate_system_status() -> Dict[str, Any]:
        """生成系统状态"""
        return {
            "status": "running",
            "uptime": f"{random.randint(12, 72)} 小时",
            "lastUpdate": datetime.now().isoformat(),
        }

    @staticmethod
    def generate_real_time_stats() -> Dict[str, Any]:
        """生成实时统计"""
        total = random.randint(15000, 20000)
        departure = random.randint(5000, 8000)
        retention = total - departure
        background = random.randint(9000, 12000)
        activity = total - background
        anomaly = random.randint(100, 200)
        normal = total - anomaly

        return {
            "totalPeople": total,
            "departure": departure,
            "retention": retention,
            "background": background,
            "activity": activity,
            "normalCount": normal,
            "anomalyCount": anomaly,
        }

    # ==================== 离场/停留识别模块 ====================
    @staticmethod
    def generate_departure_retention_data() -> Dict[str, Any]:
        """生成离场/停留识别数据"""
        times = MockDataGenerator.generate_time_labels(24)
        departure_series = MockDataGenerator.generate_random_series(24, 2000, 4000)
        retention_series = MockDataGenerator.generate_random_series(24, 6000, 10000)

        areas = ["北入口", "南入口", "东入口", "西入口", "中心区域", "停车场"]
        heatmap_data = [
            {
                "area": area,
                "departure": random.randint(800, 1500),
                "retention": random.randint(1500, 3000),
            }
            for area in areas
        ]

        return {
            "modelMetrics": {
                "accuracy": 0.85,
                "f1Score": 0.83,
                "rocAuc": 0.92,
                "precision": 0.84,
                "recall": 0.82,
            },
            "flowClassification": {
                "departure": sum(departure_series),
                "retention": sum(retention_series),
                "total": sum(departure_series) + sum(retention_series),
            },
            "timeSeriesData": {
                "times": times,
                "departure": departure_series,
                "retention": retention_series,
            },
            "heatmapData": heatmap_data,
            "confidenceDistribution": {
                "ranges": ["0.9-1.0", "0.8-0.9", "0.7-0.8", "0.6-0.7", "<0.6"],
                "counts": [6500, 4200, 1800, 800, 300],
            },
            "featureImportance": [
                {"feature": "位置语义编码", "importance": 0.28},
                {"feature": "时序移动模式", "importance": 0.24},
                {"feature": "停留时长", "importance": 0.18},
                {"feature": "轨迹方向", "importance": 0.15},
                {"feature": "速度变化", "importance": 0.15},
            ],
        }

    @staticmethod
    def generate_flow_classification() -> Dict[str, int]:
        """生成人流分类统计"""
        departure = random.randint(3000, 5000)
        retention = random.randint(8000, 12000)
        return {"departure": departure, "retention": retention, "total": departure + retention}

    @staticmethod
    def generate_trend_data(period: str = "24h") -> Dict[str, Any]:
        """生成趋势数据"""
        if period == "24h":
            times = MockDataGenerator.generate_time_labels(24)
            departure = MockDataGenerator.generate_random_series(24, 2000, 4000)
            retention = MockDataGenerator.generate_random_series(24, 6000, 10000)
        elif period == "7d":
            times = [f"第{i+1}天" for i in range(7)]
            departure = MockDataGenerator.generate_random_series(7, 50000, 80000)
            retention = MockDataGenerator.generate_random_series(7, 150000, 200000)
        else:  # 30d
            times = [f"第{i+1}天" for i in range(30)]
            departure = MockDataGenerator.generate_random_series(30, 50000, 80000)
            retention = MockDataGenerator.generate_random_series(30, 150000, 200000)

        return {"times": times, "departure": departure, "retention": retention}

    # ==================== 背景/活动区分模块 ====================
    @staticmethod
    def generate_background_activity_data() -> Dict[str, Any]:
        """生成背景/活动区分数据"""
        times = MockDataGenerator.generate_time_labels(24)
        background_series = MockDataGenerator.generate_random_series(24, 4000, 7000)
        activity_series = MockDataGenerator.generate_random_series(24, 1500, 3000)

        cluster_data = [
            {
                "clusterId": i,
                "type": random.choice(["activity", "background"]),
                "centerX": 116.39 + random.uniform(-0.01, 0.01),
                "centerY": 39.99 + random.uniform(-0.01, 0.01),
                "size": random.randint(500, 2000),
                "density": round(random.uniform(0.5, 2.0), 2),
            }
            for i in range(8)
        ]

        heatmap_data = [
            {
                "x": x,
                "y": y,
                "intensity": round(random.uniform(0.1, 1.0), 2),
                "type": random.choice(["activity", "background"]),
            }
            for x in range(10)
            for y in range(10)
        ]

        return {
            "modelMetrics": {
                "accuracy": 0.8678,
                "f1Score": 0.8631,
                "precision": 0.87,
                "recall": 0.86,
                "activityF1Improvement": 0.7676,
            },
            "flowClassification": {
                "background": sum(background_series),
                "activity": sum(activity_series),
                "total": sum(background_series) + sum(activity_series),
            },
            "timeSeriesData": {
                "times": times,
                "background": background_series,
                "activity": activity_series,
            },
            "clusterData": cluster_data,
            "featureImportance": [
                {"feature": "移动熵", "importance": 0.32},
                {"feature": "核心区域停留比", "importance": 0.26},
                {"feature": "轨迹规律性", "importance": 0.22},
                {"feature": "访问POI数量", "importance": 0.20},
            ],
            "activityHeatmap": heatmap_data,
            "decisionRules": [
                {
                    "rule": "移动熵 > 0.65 且 核心区域停留比 < 0.3",
                    "classification": "背景人流",
                    "confidence": 0.92,
                },
                {
                    "rule": "核心区域停留比 > 0.7 且 访问POI数量 > 5",
                    "classification": "活动人流",
                    "confidence": 0.88,
                },
            ],
        }

    # ==================== 异常检测模块 ====================
    @staticmethod
    def generate_anomaly_detection_data() -> Dict[str, Any]:
        """生成异常检测数据"""
        times = MockDataGenerator.generate_time_labels(24)
        normal_series = MockDataGenerator.generate_random_series(24, 13000, 16000)
        anomaly_series = MockDataGenerator.generate_random_series(24, 100, 300)

        micro_anomalies = [
            {
                "id": f"MA-{1000 + i}",
                "timestamp": (
                    datetime.now() - timedelta(minutes=random.randint(1, 60))
                ).isoformat(),
                "type": random.choice(["轨迹异常", "速度异常", "停留异常", "区域异常"]),
                "location": {
                    "x": 116.39 + random.uniform(-0.01, 0.01),
                    "y": 39.99 + random.uniform(-0.01, 0.01),
                },
                "confidence": round(random.uniform(0.85, 0.99), 2),
                "severity": random.choice(["low", "medium", "high"]),
            }
            for i in range(15)
        ]

        meso_anomalies = [
            {
                "id": f"GA-{100 + i}",
                "timestamp": (
                    datetime.now() - timedelta(minutes=random.randint(1, 60))
                ).isoformat(),
                "station": f"BS-{random.randint(1, 10):03d}",
                "type": random.choice(["突发聚集", "快速疏散", "流量异常", "密度异常"]),
                "affectedCount": random.randint(800, 2000),
                "confidence": round(random.uniform(0.90, 0.99), 2),
                "severity": random.choice(["medium", "high"]),
            }
            for i in range(5)
        ]

        return {
            "modelMetrics": {
                "micro": {"precision": 0.9959, "recall": 0.90, "featureDimensions": 30},
                "meso": {"precision": 0.95, "recall": 0.9390, "featureDimensions": 51},
            },
            "anomalyStats": {
                "normal": sum(normal_series),
                "microAnomaly": len(micro_anomalies),
                "mesoAnomaly": len(meso_anomalies),
                "total": sum(normal_series) + sum(anomaly_series),
            },
            "timeSeriesData": {
                "times": times,
                "normal": normal_series,
                "anomaly": anomaly_series,
            },
            "microAnomalies": micro_anomalies,
            "mesoAnomalies": meso_anomalies,
            "anomalyTypes": [
                {"type": "轨迹异常", "count": 42, "severity": "medium"},
                {"type": "速度异常", "count": 25, "severity": "low"},
                {"type": "停留异常", "count": 18, "severity": "high"},
                {"type": "区域异常", "count": 10, "severity": "medium"},
            ],
            "microFeatureImportance": [
                {"feature": "移动性特征", "importance": 0.25},
                {"feature": "时空特征", "importance": 0.22},
                {"feature": "轨迹特征", "importance": 0.20},
                {"feature": "行为特征", "importance": 0.18},
                {"feature": "上下文特征", "importance": 0.15},
            ],
            "mesoFeatureImportance": [
                {"feature": "统计特征", "importance": 0.28},
                {"feature": "密度特征", "importance": 0.24},
                {"feature": "流量特征", "importance": 0.22},
                {"feature": "时序特征", "importance": 0.16},
                {"feature": "空间特征", "importance": 0.10},
            ],
            "confidenceDistribution": {
                "ranges": ["极高(>0.95)", "高(0.85-0.95)", "中(0.75-0.85)", "低(<0.75)"],
                "micro": [35, 42, 18, 0],
                "meso": [4, 1, 0, 0],
            },
        }

    @staticmethod
    def generate_prediction_result(prediction_type: str = "departure") -> Dict[str, Any]:
        """生成预测结果"""
        prediction = random.choice(["departure", "retention"])
        confidence = round(random.uniform(0.75, 0.99), 2)

        return {
            "prediction": prediction,
            "confidence": confidence,
            "probability": {
                "departure": confidence if prediction == "departure" else 1 - confidence,
                "retention": confidence if prediction == "retention" else 1 - confidence,
            },
        }


# 创建全局实例
mock_generator = MockDataGenerator()
